package net.freebytes.ssmp.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.freebytes.ssmp.entity.Permission;
import net.freebytes.ssmp.entity.Role;
import net.freebytes.ssmp.entity.User;
import net.freebytes.ssmp.exception.UserException;
import net.freebytes.ssmp.mapper.UserMapper;
import net.freebytes.ssmp.util.CommonUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author 千里明月
 * @date 2021/7/20
 **/
@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    @Value("${init.username}")
    private String username;
    @Value("${init.password}")
    private String password;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermService permService;


    @PostConstruct
    public void initUser() {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setName("超级管理员");
        if (!exist(user.getUsername())) {
            insert(user);
        }
    }

    /**
     * 新建用户
     *
     * @param user
     * @return
     */
    public boolean insert(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUsername, user.getUsername());
        List<User> list = super.list(queryWrapper);
        if (list != null && list.size() > 0) {
            throw new RuntimeException("账号已经存在");
        }
        String salt = RandomStringUtils.randomAlphabetic(20);
        user.setSalt(salt);
        user.setPassword(CommonUtil.salt(user.getPassword(), salt));
        user.setCreateTime(new Date());
        return super.save(user);
    }

    public User getUserByName(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUsername, username);
        User user = super.getOne(queryWrapper);
        return user;
    }

    public List<User> listAll() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //隐藏敏感信息
        queryWrapper.lambda().select(User::getName, User::getId);
        return this.list(queryWrapper);
    }

    /**
     * 获取当前用户Session
     *
     * @return
     */
    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }


    public boolean exist(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getUsername, username);
        User one = super.getOne(wrapper);
        return one != null;
    }


    public boolean editName(String id, String name) {
        User user = super.getById(id);
        user.setName(name);
        return super.updateById(user);
    }

    /**
     * 从数据库中加载用户角色权限详情
     *
     * @author 千里明月
     * @date 2021/7/23
     **/
    public User userDetail(String id) {
        QueryWrapper<User> wrapper = new QueryWrapper();
        wrapper.lambda().select(User::getId, User::getUsername, User::getName).eq(User::getId, id);
        User user = getOne(wrapper);
        if (user == null) {
            throw new UserException("用户不存在!");
        }

        List<Role> roles = roleService.getBaseMapper().getRoleByUserId(id);

        for (Role role : roles) {
            List<Permission> permission = permService.getBaseMapper().getPermissionByRoleId(Arrays.asList(role.getId()));
            role.setPermissions(permission);
        }
        user.setRoles(roles);
        return user;
    }

    /**
     * 从缓存中加载用户详情
     *
     * @author 千里明月
     * @date 2021/7/23
     **/
    public User cacheUserDetail(String id) {
        User user = CommonUtil.currentUser();
        List<Role> roles = roleService.cacheRoleByUserId(user.getId());
        List<Permission> permissions = permService.cacheAllPermissionByUid(user.getId());
        user.setRoles(roles);
        user.setPermissions(permissions);
        return user;
    }

}
